<?php

namespace PKApp\Content;

use PKApp\Content\Classes\TraitContent;
use PKApp\Model\Classes\TraitModel;
use PKCommon\Controller\AdminController;
use PKFrame\DataHandler\Arrays;

class AdminBatReplace extends AdminController
{
    use TraitContent, TraitModel;

    public function Main()
    {
        $this->fetch('bat_replace_content');
    }

    public function ApiByBatReplace()
    {
        $str_search = $this->checkPostFieldIsEmpty('search', 'Empty_replace_search');
        $str_replace = $this->checkPostFieldIsEmpty('replace', 'Empty_replace_str');
        $modelId = $this->getIdOfModel();
        $service_content = $this->serviceOfContent($modelId);
        $list_field_req = request()->post('listField');
        Arrays::Is($list_field_req) ?: $this->noticeByJson('Empty_replace_field');
        $list_field = Arrays::Column($list_field_req, 'value');
        $list_field_base = array_keys(dict('fieldList_IsSystem', 'model'));
        $listReplace_base = $listReplace_data = [];
        foreach ($list_field as $item) {
            !in_array($item, $list_field_base) ?: $listReplace_base[] = $item;
        }
        $list_field_db = $this->serviceOfField()->GetList(['modelId' => $modelId,
            'field' => Arrays::Column($list_field_req, 'value')], ['field', 'isList']);
        if (Arrays::Is($list_field_db)) {
            foreach ($list_field_db as $item) {
                (bool)$item['isList'] ? $listReplace_base[] = $item['field'] : $listReplace_data[] = $item['field'];
            }
        }
        !Arrays::Is($listReplace_base) ?: $service_content->ReplaceFieldContent($listReplace_base, $str_search, $str_replace, true);
        !Arrays::Is($listReplace_data) ?: $service_content->ReplaceFieldContent($listReplace_data, $str_search, $str_replace, false);
        $this->inputSuccess();
    }
}